<?php namespace Entry\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB as DB;
use Stats\Models\Test\Test;
use Entry\User;
use Illuminate\Support\Facades\View;
use Crypt;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    protected static $verbose_name = "users";
    protected static $permissions = [];

    protected function makeQuery($query){

        $role_id =  \Input::get('role_id',0);
        if($role_id){
            $query = $query->whereHas("roles",function($query) use($role_id){
                $query->where("role_id",$role_id);
            });
        }

        if($f = \Input::get('f')) {
            $query = $query->where(function ($query) use ($f) {
                foreach ($f as $key => $value) {
                    if ($value == 'all' || !$value) {
                        continue;
                    }else {
                        $query = $query->where($key, '=', $value);
                    }
                }
            });
        }

//        if ($filter = \Input::get('filter')) {
//            switch ($filter) {
//                case 'doing':
//                    $query = $query->ownedBy(1)->whereIn('status', [1,3,4]);
//                    break;
//                case 'watcher':
//                    $query = $query->watchedBy(1);
//                    break;
//                default:
//                    break;
//            }
//        }

        return $query;
    }


    public function index(){
        $query = $this->makeQuery(User::with('roles'));
        $items = $query->paginate(15);
        return view("Users.index",[
            'alluser'=>$items,
        ]);
    }

    public function create(){
        return view("Users.create");
    }

    public function store(Request $request){
        $this->validate($request, [
            'user.username' => 'required|unique:users,username',
            'user.email' => 'required|unique:users,email',
        ]);
        $data =  \Input::all();
        $info = $data['user'];
        $info['password'] = bcrypt($data['user']['password']);
        $user = new User();
        $user->username=$info['username'];
        $user->email=$info['email'];
        $user->password=$info['password'];
        $user->realname=$info['realname'];
        $user->mobile=$info['mobile'];
        $user->save();
        return redirect(route('admin.user.index'));
    }
}